import {
	getToken,
	showToast,
	parseTime
} from '@/utils/common.js'

import {
	platform
} from '@/utils/platform.js'


let systemInfo = uni.getSystemInfoSync()
let isIOS = systemInfo.platform === 'ios'
const defaultColor = "#02a074"

export function downloadFromURL({
	url = '',
	fileName = '文件'
}) {
	return new Promise(async (resolve, reject) => {
		try {
			let res = await downLoadFile(url);
			let tempFilePath = res.tempFilePath
			if (platform !== '4') {
				let content = '下载成功，是否打开?'
				resolve(res)
				uni.showModal({
					title: '下载成功',
					content,
					confirmColor: defaultColor,
					confirmText: '打开',
					success(res) {
						if (res.confirm) {
							openFile(tempFilePath);
						} else if (res.cancel) {}
					},
				})
			} else {
				let {
					tempFilePath
				} = res;
				let saveRes = await saveFile(tempFilePath, fileName, url);
				if (saveRes.savedFilePath) {
					resolve({
						...saveRes,
						tempFilePath: saveRes.savedFilePath
					})
				} else {
					resolve(saveRes)
				}
			}
		} catch (e) {

			//TODO handle the exception
		}
	})
}

export function previewFromURL(url) {
	return new Promise(async (resolve, reject) => {
		try {
			let res = await downLoadFile(url);
			let tempFilePath = res.tempFilePath
			await openFile(tempFilePath);
			resolve(res)
		} catch (e) {
			//TODO handle the exception
		}
	})
}


export function downLoadFile(url) {
	let header = {
		token: 'Bearer ' + getToken(),
	}
	uni.showLoading({
		title: "下载中"
	})
	return new Promise(async (resolve, reject) => {
		uni.downloadFile({
			url: url,
			header,
			success: (res) => {

				if (res.statusCode === 200) {
					uni.hideLoading()
					resolve(res)
				} else {
					uni.hideLoading()
					showToast('下载失败', true)
					reject(res)
				}
				console.log('downLoadFile_ok', res)
			},
			fail: (err) => {
				uni.hideLoading()
				showToast('下载失败', true)
				console.log('downLoadFile_fail', err)
				reject(err)
			},
		})
	})
}

export function openFile(url) {
	return new Promise(async (resolve, reject) => {
		uni.openDocument({
			//打开文件
			filePath: url, //文件名
			showMenu: true, //右上角是否显示(...)
			success(res) {
				console.log(res)
				resolve(res)
			},
			fail(err) {
				console.log('openDocument:fail', err)
				// #ifdef APP-PLUS
				if (isIOS) {
					showToast('打开文件失败')
				} else {
					uni.showModal({
						title: '打开文件失败',
						content: '请先安装Office应用',
						confirmColor: defaultColor,
						confirmText: '确定',
						showCancel: false,
						success: (res) => {},
					})
				}
				// #endif
				reject()
			},
		})
	})
}



export function saveFile(url, filename, resourceUrl) {
	uni.showLoading({
		title: '加载中',
	})
	return new Promise(async (resolve, reject) => {
		uni.saveFile({
			tempFilePath: url,
			success: (res) => {
				uni.hideLoading()
				let filePath = res.savedFilePath
				resolve(res)
				let content = '下载成功，是否打开?'
				//#ifdef APP-PLUS
				//ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹，保存文件并改名
				if (!isIOS) {
					fSetFileName(resourceUrl, filename);
				}
				if (!isIOS) {
					content =
						'文件已保存至文件管理器 Android/data/com.shenjiying.receipt/downloads/ 目录，是否打开?'
				}
				// #endif
				uni.showModal({
					title: '下载成功',
					content,
					confirmColor: defaultColor,
					confirmText: '打开',
					success(res) {
						if (res.confirm) {
							openFile(filePath)
						} else if (res.cancel) {}
					},
				})
			},
			fail: (err) => {
				console.log('saveFile_fail', err)
				uni.hideLoading()
				uni.showModal({
					title: '提示',
					content: '文件保存失败',
					showCancel: false, //是否显示取消按钮
					success: function(result) {},
				})
				reject(err)
			},
		})
	})
}



export function downLoad(file) {
	return new Promise(async (resolve, reject) => {
		uni.showLoading({
			title: '加载中',
		})
		// let filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.xlsx`; //导出的文件名
		let filePath = `${
      wx.env.USER_DATA_PATH
    }/zhangdan-${new Date().getTime()}.xlsx` //导出的文件名
		console.log('filePath', filePath)
		try {
			let fm = uni.getFileSystemManager() //获取文件管理器
			fm.writeFile({
				//写入文件
				filePath, //文件名
				data: file, //数据
				encoding: 'binary',
				success: (res) => {
					console.log('writeFile', res)
					uni.hideLoading()
					resolve(res)
					uni.showModal({
						title: '下载成功',
						content: '是否打开?',
						confirmColor: defaultColor,
						confirmText: '打开',
						success(res) {
							if (res.confirm) {
								uni.openDocument({
									//打开文件
									filePath, //文件名
									showMenu: true, //右上角是否显示(...)
									success(res) {
										console.log(res)
									},
								})
							} else if (res.cancel) {}
						},
					})
				},
				fail: (err) => {
					reject(err)
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: '文件下载失败',
						showCancel: false, //是否显示取消按钮
						success: function(result) {},
					})
				},
			})
		} catch (e) {
			uni.hideLoading()
			this.showToast('写入文件失败')
			console.log(e)
			reject(e)
			//TODO handle the exception
		}
	})
}


export function clickDownload({
	url,
	filename = '账单导入模板',
}) { //点击下载
	//下载地址
	let downloadUlr = url;
	//获取地址后缀
	//下载文件为非图片和视频的文件
	const downloadTaskt = uni.downloadFile({
		url: url, //下载地址接口返回
		success: (data) => {
			uni.hideLoading()
			if (data.statusCode === 200) {
				var sFilePath = data.tempFilePath
				var sFileName = downloadUlr.split('/')[downloadUlr.split('/').length - 1]; //原来的文件名

				//#ifdef APP-PLUS
				//文件保存到本地
				uni.saveFile({
					tempFilePath: data.tempFilePath, //临时路径
					success: function(res) {
						var savedFilePath = res.savedFilePath;
						//ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹，保存文件并改名
						if (!isIOS) {
							fSetFileName(downloadUlr, filename, res.savedFilePath, sFilePath);
						}
						let content = '下载成功，是否打开?'
						if (!isIOS) {
							content =
								'文件已保存至文件管理器 Android/data/com.shenjiying.receipt/downloads/ 目录，是否打开?'
						}
						uni.showModal({
							title: '下载成功',
							content: content,
							confirmColor: defaultColor,
							confirmText: '打开',
							success(res) {
								if (res.confirm) {
									openFile(savedFilePath)
								} else if (res.cancel) {}
							},
						})
					},
					fail: function(res) {
						showToast('保存文件失败', true)
					}
				});
				//#endif
			} else {
				showToast('下载失败', true)
			}
		},
		fail: (err) => {
			showToast('下载失败', true)
		}
	})
}



//点击下载END
// 给下载的文件重命名
/**
 * @param {String} url 文件路径 
 * @param {String} filename 文件重命名前缀(例如:账单/开票记录)
 * 
*/
function fSetFileName(url, filename) {
	// var sFileName = sFileName.split('/')[sFileName.split('/').length - 1]; //原来的文件名
	let type = url.substring(url.lastIndexOf('.'))
	let date = new Date()
	let filenameConcat = `${filename}-${parseTime(date)}`

	//file://storage/emulated/0  固定写法，
	//Download：文件保存的文件夹名称，试了其他名称但是在手机文件管理中没能找到文件，使用download后可以
	//type：文件后缀
	let basePath = '_downloads/'
	let fullPath = basePath + filenameConcat + type
	// 'url下载地址（和上面的一样）'
	let dtask = plus.downloader.createDownload(url, {
			// filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹，把文件存储进去，并更改会原名
			filename: fullPath //在手机存储更目录创建一个叫AAA的文件夹，把文件存储进去，并更改会原名
		},
		(d, status) => {
			if (status == 200) {
				let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);

			} else {
				//下载失败
				plus.downloader.clear(); //清除下载任务
			}
		})
	dtask.start();
}

export function downloadImageFromURL(url = "") {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			fail: function(res) {
				uni.showModal({
					title: '提示',
					content: '保存失败',
				})
				reject(res)
			},
			success: function(res) {
				resolve(res)
			},
		})

	})
}